package com.dai.zhenfujin;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.base.BaseActivity;
import com.dai.zhenfujin.bean.ResBdBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.my.MyInfoActivity;
import com.dai.zhenfujin.my.activity.AboutAgreementActivity;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import java.util.HashMap;
import java.util.Map;


/**
 * 立即注册
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private RequestQueue queue;
    private EditText etNumber, etPassword, etsms,register_img,login_invite;
    private TextView tvVerification,apaRegister,title_textview,tv_user_info,tv_zhengce;
    private Button buttonl;
    private ImageView title_imageview,register_show_img;
    private FrameLayout fl_img;
    private String phone;
    private String verifyId;
    private VerificationCodeCountTimer verificationCodeCountTimer;
    private String ver_env;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        queue = Volley.newRequestQueue(this);
        etNumber = findViewById(R.id.login_number);
        etPassword = findViewById(R.id.login_password);
        etsms = findViewById(R.id.login_sms);
        title_textview = findViewById(R.id.title_textview);
        register_show_img = findViewById(R.id.register_show_img);
        register_img = findViewById(R.id.register_img);

        tvVerification = findViewById(R.id.login_verification);
        apaRegister = findViewById(R.id.apa_register);
        buttonl = findViewById(R.id.login_button);
        fl_img = findViewById(R.id.fl_img);
        login_invite = findViewById(R.id.login_invite);
        tv_user_info = findViewById(R.id.tv_user_info);
        tv_zhengce = findViewById(R.id.tv_zhengce);

        title_textview.setText("注册");
        verificationCodeCountTimer = new VerificationCodeCountTimer(61100, 1000);


        buttonl.setOnClickListener(this);
        fl_img.setOnClickListener(this);
        tvVerification.setOnClickListener(this);
        register_show_img.setOnClickListener(this);
        login_invite.setOnClickListener(this);
        tv_user_info.setOnClickListener(this);
        tv_zhengce.setOnClickListener(this);
        //得到图形验证码
        getVerify();
    }

    private void getVerify() {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params.put("req_bd", params2);
        HttpClient.post(this, Constants.CODE_URL, params, new CallBack<ResBdBean>() {
            @Override
            public void onSuccess(ResBdBean resultBean) {
                verifyId = resultBean.verifyId;
                ver_env = resultBean.ver_env;
                Glide.with(LoginActivity.this).load(resultBean.url).into(register_show_img);
                // etSms.setText(code);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_button: //注册
                register();
                break;
            case R.id.login_verification://获取验证码
                getCode();
                break;
            case R.id.fl_img://
                finish();
                break;
            case R.id.register_show_img://得到图形验证码
                getVerify();
                break;
            case R.id.tv_user_info:
                Intent meg = new Intent(this, AboutAgreementActivity.class);
                meg.putExtra("type",0);
                startActivity(meg);
                break;
            case R.id.tv_zhengce:
                Intent intent = new Intent(this,AboutAgreementActivity.class);
                intent.putExtra("type",1);
                startActivity(intent);
                break;
        }
    }

    /**
     * 获取验证码
     */
    private void getCode() {
        if (TextUtils.isEmpty(etNumber.getText().toString().trim())){
            UIUtils.showToastSafe("请输入手机号码");
            return;
        }

        if (TextUtils.isEmpty(register_img.getText().toString().trim())) {
            UIUtils.showToastSafe("请输入图形验证码");
            return;
        }

        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();

        params2.put("mobile", etNumber.getText().toString());
        params2.put("type", "1");
        params2.put("verifyId", verifyId);
        params2.put("ver_env", ver_env);
        params2.put("verifyCode", register_img.getText().toString().trim());
        params.put("req_bd", params2);


        HttpClient.post(this, Constants.GETCODE, params, new CallBack<ResBdBean>() {
            @Override
            public void onSuccess(ResBdBean resultBean) {
                if (resultBean.getSms_code().equals("true")){
                    UIUtils.showToastSafe("验证码已发送");
                    verificationCodeCountTimer.start();
                }else {
                    UIUtils.showToastSafe("获取过于频繁，请稍后一分钟后在试");
                }
            }
        });
    }



    private void register() {
        phone = etNumber.getText().toString().trim();
        if (TextUtils.isEmpty(etNumber.getText().toString().trim())){
            UIUtils.showToastSafe("请输入手机号码");
            return;
        }
        if (TextUtils.isEmpty(register_img.getText().toString().trim())) {
            UIUtils.showToastSafe("请输入图形验证码");
            return;
        }
        if (TextUtils.isEmpty(etsms.getText().toString().trim())){
            UIUtils.showToastSafe("请输入验证码");
            return;
        }
        if (TextUtils.isEmpty(etPassword.getText().toString().trim())){
            UIUtils.showToastSafe("请输入6-12位密码");
            return;
        }

        if (etPassword.getText().toString().trim().length() < 6){
            UIUtils.showToastSafe("请输入6-12位密码");
            return;
        }


        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();

        params2.put("mobile", etNumber.getText().toString());
        params2.put("code", etsms.getText().toString());
        params2.put("invite", login_invite.getText().toString().trim());
        params2.put("pwd", UIUtils.Md5(etPassword.getText().toString()));
        SPUtils.put(this,"invite",login_invite.getText().toString().trim());

        params.put("req_bd",  params2);

        HttpClient.post(this, Constants.USER_REGISTER, params, new CallBack<ResBdBean>() {
            @Override
            public void onSuccess(ResBdBean resultBean) {
                 SPUtils.put(LoginActivity.this,"regist",true);
                try {
                    EMClient.getInstance().createAccount(phone + "", "zfj123");
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                String token = resultBean.getAccess_token();
                SPUtils.put(LoginActivity.this, Constants.TOKEN, token);
                EMClient.getInstance().login(phone, "zfj123", new EMCallBack() {//回调
                    @Override
                    public void onSuccess() {
                        EMClient.getInstance().chatManager().loadAllConversations();
                        SPUtils.put(LoginActivity.this, "login", true);
                        Log.d("main", "登录聊天服务器成功");
                        if (resultBean.name_state == 2) { //未完善资料
                            UIUtils.showToastSafe("请先完善资料");
                            startActivity(new Intent(LoginActivity.this, MyInfoActivity.class)
                                    .putExtra("type", 1));
                            finish();
                        } else {
                            SPUtils.put(LoginActivity.this, "welcome", true);
                            SPUtils.put(LoginActivity.this, Constants.USER_MOBILE, phone);
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        }
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }

                    @Override
                    public void onError(int code, String message) {
                        if (200 == code) {
                            UIUtils.showToastSafe("用户已经登录");
                        } else {
                            UIUtils.showToastSafe("登录聊天服务器失败");
                        }
                        Log.d("main", "登录聊天服务器失败！");
                        Log.d("main", code + message);
                    }
                });
            }
        });
    }

    class VerificationCodeCountTimer extends CountDownTimer {

        private VerificationCodeCountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            int time = (int) (Math.round((double) millisUntilFinished / 1000) - 1);
            tvVerification.setTextColor(getResources().getColor(R.color.btn_blue_normal));
            tvVerification.setText(time + "s");
        }

        @Override
        public void onFinish() {
            tvVerification.setText("获取验证码");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (verificationCodeCountTimer != null) {
            verificationCodeCountTimer.cancel();
        }
    }
}
